import Page from "@/components/page";
import { Button, Input, View } from "@tarojs/components";
import React, { useEffect, useState } from "react";
import { accountMemberType, accountType, fixedIncomeType } from "@/types";
import moment from "moment";
import { observer } from "mobx-react";
import Taro from "@tarojs/taro";
import Members from "./members";
import http from "@/request";
import FixedIncome from "@/pages/accounts/accountDetail/fixedIncome";
import { AtModal, AtModalHeader, AtModalContent, AtModalAction } from "taro-ui";
import viewMode from "@/store/viewMode";
import FixedIncomeModal from "./fixedIncomeModal";
import account from "@/store/account";
import user from "@/store/user";
import { HideLoading, ShowLoading, ShowToast } from "@/utils";
import PageNav from "@/components/pageNav";
import MemberEditer from "./memberEditer";

import "./index.scss"

const AccountDetail: React.FC = observer(() => {
    const [accountData, setAccountData] = useState<accountType>()
    const [showType, setShowType] = useState<string>('member')
    const [accountId, setAccountId] = useState<number>()
    const [editNameVisible, setEditNameVisible] = useState(false)
    const [editMemberVisible, setEditMemberVisible] = useState(false)
    const [fixedIncomeEditVisible, setFixedIncomeEditVisible] = useState(false)
    const [member, setMember] = useState<accountMemberType>()
    const [fixedIncome, setFixedIncome] = useState<fixedIncomeType>({
        accountId: account.activeAccount?.id,
        amount: 0,
        bookDate: moment().date(),
        cycle: 1,
        name: '',
        type: 0,
        userName: user.info?.userName,
        status: 1
    })

    const setAccountFormItem = (val, key) => {
        setAccountData({
            ...(accountData || {}),
            [key]: val
        })
    }

    const switchShowType = () => {
        const type = showType === 'member' ? 'fixIncome' : 'member'
        setShowType(type)
    }

    const getAccountInfo = () => {
        if (!accountId) return
        ShowLoading()
        http.get(`/account/detail/${accountId}`).then(res => {
            console.log(res.data);
            setAccountData(res.data)
            HideLoading()
        }).catch(err => {
            ShowToast(err.msg || '获取账本详情失败')
        })
    }

    const closeModal = () => {
        setEditNameVisible(false)
    }

    const modalOnSure = () => {
        const request = editMemberVisible ? http.post('/account-user/update', {
            id: member?.id,
            initAmount: member?.initAmount
        }) : editNameVisible ? http.post('/account/addOrUpdate', {
            name: accountData?.name,
            id: accountData?.id
        }) : null
        if (request) {
            request.then(_ => {
                ShowToast('数据保存成功')
                getAccountInfo()
                account.doUpDateAccount()
                closeModal()
            }).catch(err => {
                ShowToast(err.msg || '数据保存失败')
            })
        }
    }

    const memberEdit = (member) => {
        setMember(member);
        setEditMemberVisible(true)
    }

    const memberDelete = (member: accountMemberType) => {
        Taro.showModal({
            title: `是否删除成员:${member.userName}`,
            content: `成员账单仍将保留，当前账本下其初始资金和固定收支将被同步删除，是否继续？`,
            success: (res) => {
                if (res.confirm) {
                    ShowLoading()
                    http.post('/account-user/delete', member).then(_ => {
                        HideLoading()
                        account.doUpDateAccount()
                        getAccountInfo()
                    }).catch(err => {
                        ShowToast(err.msg || '删除成员失败')
                    })
                }
            }
        })
    }

    const openFixedIncomeModal = (fixedIncome: fixedIncomeType) => {
        setFixedIncome(fixedIncome)
        setFixedIncomeEditVisible(true)
    }

    const deleteFixedIncome = (fixedIncome: fixedIncomeType) => {
        Taro.showModal({
            title: '提示',
            content: `是否删除固定收支[${fixedIncome.name}]？`,
            success: (res) => {
                if (res.confirm) {
                    ShowLoading()
                    http.delete(`/fixedIncome/delete/${fixedIncome.id}`).then(_ => {
                        ShowToast('删除成功')
                        getAccountInfo()
                        account.doUpDateAccount()
                    }).catch(err => {
                        ShowToast(err.msg || '删除失败')
                    })
                }
            }
        })
    }

    const saveFixedIncomeEdit = (data: fixedIncomeType) => {
        if (!data.name) {
            ShowToast('请输入收支名称')
            return
        }
        if (!data.amount && data.amount! == 0) {
            ShowToast('收支金额不能为空')
            return
        }
        setFixedIncomeEditVisible(false)
        const { createTime, expirationDate, effectiveDate, ...params } = data
        http.post('/fixedIncome/addOrUpdate', params).then(_ => {
            getAccountInfo()
            account.doUpDateAccount()
            ShowToast('数据保存成功')
        }).catch(err => {
            ShowToast(err.msg || '数据保存失败')
        }).finally(() => {
        })
    }

    useEffect(() => {
        viewMode.setBehind(editNameVisible || fixedIncomeEditVisible)
    }, [editNameVisible, fixedIncomeEditVisible])

    useEffect(() => {
        getAccountInfo()
    }, [accountId])

    Taro.useLoad((params) => {
        setAccountId(Number(params.accountid))
    })

    return (
        <Page className="account-page page-background text-main-color flex-column flex-item">
            <PageNav showBack className="report-page-header need-filter">账本详情</PageNav>
            <View className="account-form card-background need-filter">
                <View className="form-item-title font-size28">{accountData?.id ? '编辑账本' : '新建账本'}</View>
                <View className="form-item-container">
                    <View className="form-item-label">账本名称</View>
                    <View className="form-input flex-row flex-item">
                        <View className="form-input-value flex1">{accountData?.name}</View>
                        <View onClick={() => setEditNameVisible(true)} className="btn font-size40 iconfont icon-bianji"></View>
                    </View>
                </View>
                <View className="form-item-container">
                    <View className="form-item-label">创建人</View>
                    <View className="form-input">{accountData?.createUserName}</View>
                </View>
                <View className="form-item-container">
                    <View className="form-item-label">创建时间</View>
                    <View className="form-input">{moment().format('YYYY-MM-DD HH:mm:ss')}</View>
                </View>
            </View>
            <View className="account-form card-background need-filter">
                <View className="type-switch font-size28 flex-row flex-item text-main-color">
                    <View onClick={switchShowType} className={`type-item ${showType === 'member' ? 'active' : ''}`}>
                        <View className="type-name">成员信息</View>
                        <View className="bottom-line bg-contrast-color"></View>
                    </View>
                    <View onClick={switchShowType} className={`type-item ${showType === 'fixIncome' ? 'active' : ''}`}>
                        <View className="type-name">固定收支</View>
                        <View className="bottom-line bg-contrast-color"></View>
                    </View>
                    <View className="flex1"></View>
                    <View className="right-content">左划编辑/删除</View>
                </View>
                {showType === 'member' ?
                    <Members
                        accountData={accountData}
                        members={accountData?.members}
                        onChange={getAccountInfo}
                        onMemberEdit={memberEdit}
                        onMemberDelete={memberDelete}>
                    </Members> :
                    <FixedIncome
                        key={new Date().getTime()}
                        fixedIncomes={accountData?.fixedIncomes}
                        accountData={accountData}
                        onEdit={openFixedIncomeModal}
                        onDetele={deleteFixedIncome}
                        onAdd={openFixedIncomeModal}>
                    </FixedIncome>
                }
            </View>
            <FixedIncomeModal
                onCancel={() => setFixedIncomeEditVisible(false)}
                onSure={saveFixedIncomeEdit}
                account={accountData}
                fixedData={fixedIncome}
                visible={fixedIncomeEditVisible}>
            </FixedIncomeModal>
            <AtModal isOpened={editNameVisible}
                className="edit-modal"
                onClose={closeModal}>
                <AtModalHeader>编辑账本名称</AtModalHeader>
                <AtModalContent>
                    {
                        editNameVisible ? <Input className="target-val-input" value={`${accountData?.name}`} onInput={(e) => {
                            const target = e.target as HTMLInputElement
                            setAccountFormItem(target.value, 'name')
                        }}></Input> : null
                    }
                </AtModalContent>
                <AtModalAction>
                    <Button onClick={closeModal}>取消</Button>
                    <Button onClick={modalOnSure}>确定</Button>
                </AtModalAction>
            </AtModal>

            <MemberEditer
                show={editMemberVisible}
                accountId={accountId}
                memberData={member}
                onClose={() => setEditMemberVisible(false)}
                onChange={getAccountInfo}>
            </MemberEditer>
        </Page>
    )
}
)

export default AccountDetail